/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.cax.utils;

import com.comac.ins.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CaxFileConvertUtil {

    /**
     * 自研 CAD
     */
    private static final String CAD_CONVERT_URL1 = "/data2/cax";

    /**
     * 九韶 CAD
     */
    private static final String CAD_CONVERT_URL2 = "/data2/cax/amcax/Release/bin";

    /**
     * 自研 CAE
     */
    private static final String CAE_CONVERT_URL1 = "/data2/cax/cae_self_develop";

    /**
     * exchange CAE
     */
    private static final String CAE_CONVERT_URL2 = "/data2/cax/cae_ceetron";

    /**
     * 云道 CAE
     */
    private static final String CAE_CONVERT_URL3 = "/data2/cax/cae_yundao/Release";

    /**
     * CAD 结构化脚本（STEP）
     */
    private static final String CAD_STRUCTURED_URL = "/home/sfrj/StepToMySQLImporter/build";

    private static final String CAD_STRUCTURED_TOOL = "./StepToMySQLImporter";
    private static final String CAD_CONVERT_TOOL1 = "./dataExchange";
    private static final String CAD_CONVERT_TOOL2 = "sh amcaxExchange.sh";

    private static final String CAE_CONVERT_TOOL1 = "./cae_convertor_v2";
    private static final String CAE_CONVERT_TOOL2 = "./cae_convertor";
    private static final String CAE_CONVERT_TOOL3 = "./yundao.sh";

    public static List<String> caeGeneralType = new ArrayList<>();
    public static List<String> cadGeneralType = new ArrayList<>();

    public static void dataInit() {
        caeGeneralType.add("vtk");
        caeGeneralType.add("gmesh");
        cadGeneralType.add("STEP");
        cadGeneralType.add("IGES");
        cadGeneralType.add("STL");
        cadGeneralType.add("OBJ");
    }

    public static boolean cadConvert(String inputFilePath, String inputTypeStr, String outputTypeStr, String status) throws IOException, InterruptedException {
        String logUrl = FileUtils.changeFileExtension(inputFilePath, "log");
        // 特殊处理CATIA装配件
        List<String> cadGeneralType = new ArrayList<>();
        cadGeneralType.add("CATProduct");
        cadGeneralType.add("CATPart");
        String newExtension;
        if (cadGeneralType.contains(outputTypeStr)) {
            newExtension = outputTypeStr;
        } else if ("Parasolid".equals(outputTypeStr)) {
            newExtension = "x_t";
        } else {
            newExtension = outputTypeStr.toLowerCase();
        }
        String outputFilePath;
        String outputFilePath2 = "";
        String inputFilePath2 = inputFilePath;
        // 处理装配体ZIP包，解压(CATIA CATProduct、solidworks Sldasm)
        if ("CATProduct".equals(inputTypeStr) || "Sldasm".equals(inputTypeStr)) {
            String directoryPath = StringUtils.getDirectoryPath(inputFilePath);
            String zipStr = "unzip " + inputFilePath + " -d " + directoryPath;
            String[] cmd = new String[]{"/bin/sh", "-c", zipStr};
            ExecUtils.exec(cmd, logUrl);
            String fileName = StringUtils.extractFileName(inputFilePath);
            String realInputTypeStr = "CATProduct".equals(inputTypeStr) ? inputTypeStr : inputTypeStr.toLowerCase();
            inputFilePath2 = directoryPath + "/" + fileName + "/" + fileName + "." + realInputTypeStr;
        }
        // 处理输出装配体，增加装配体文件夹(CATIA CATProduct、solidworks Sldasm)
        if ("CATProduct".equals(outputTypeStr) || "Sldasm".equals(outputTypeStr)) {
            outputFilePath2 = StringUtils.getDirectoryPath(inputFilePath) + "/" + StringUtils.extractFileName(inputFilePath);
            File dirPath = new File(outputFilePath2);
            dirPath.mkdir();
            outputFilePath = outputFilePath2 + "/" + StringUtils.extractFileName(inputFilePath) + "." + newExtension;
        } else {
            outputFilePath = FileUtils.changeFileExtension(inputFilePath, newExtension);
        }
        // 检测文件是否生成，返回boolean
        String str = initCadStr(inputFilePath2, inputTypeStr, outputTypeStr, status, outputFilePath);
        String[] cmd = new String[]{"/bin/sh", "-c", str};
        ExecUtils.exec(cmd, logUrl);
        // 压缩文件
        if ("CATProduct".equals(outputTypeStr) || "Sldasm".equals(outputTypeStr)) {
            zipDirectory(outputFilePath2);
        }
        // STEP 结构化
//        if ("STEP".equals(inputTypeStr)) {
//            String strStructured = "cd " + CAD_STRUCTURED_URL + " && " + CAD_STRUCTURED_TOOL + " " + inputFilePath;
//            String[] cmdStructured = new String[]{"/bin/sh", "-c", strStructured};
//            ExecUtils.exec(cmdStructured, null);
//        }
        return new File(outputFilePath).exists();
    }

    public static boolean caeInputConvert(String inputFilePath, String outputTypeStr, String status) throws IOException, InterruptedException {
        String logUrl = FileUtils.changeFileExtension(inputFilePath, "log");
        String outputFilePath = initOutputFilePath(inputFilePath, outputTypeStr);
        // 检测文件是否生成，返回boolean
        String str = initCaeStr(inputFilePath, outputTypeStr, status, outputFilePath);
        String[] cmd = new String[]{"/bin/sh", "-c", str};
        ExecUtils.exec(cmd, logUrl);
        dataInit();
        // 压缩文件夹
        if (caeGeneralType.contains(outputTypeStr)) {
            zipDirectory(inputFilePath);
        }
        return new File(outputFilePath).exists();
    }

    public static boolean caeOutputConvert(String inputFilePath, String outputTypeStr, String status) throws IOException, InterruptedException {
        String logUrl = FileUtils.changeFileExtension(inputFilePath, "log");
        String outputFilePath = initOutputFilePath(inputFilePath, outputTypeStr);
        // 检测文件是否生成，返回boolean
        String str = initCaeStr(inputFilePath, outputTypeStr, status, outputFilePath);
        String[] cmd = new String[]{"/bin/sh", "-c", str};
        ExecUtils.exec(cmd, logUrl);
        dataInit();
        // 压缩文件夹
        if (caeGeneralType.contains(outputTypeStr)) {
            zipDirectory(inputFilePath);
        }
        return new File(outputFilePath).exists();
    }

    public static void zipDirectory(String inputFilePath) throws IOException, InterruptedException {
        String logUrl = FileUtils.changeFileExtension(inputFilePath, "log2");
        String directoryPath = StringUtils.getDirectoryPath(inputFilePath);
        String fileName = StringUtils.extractFileName(inputFilePath);
        String str = "cd " + directoryPath + " && " + " zip -r " + fileName + ".zip " + fileName;
        String[] cmd = new String[]{"/bin/sh", "-c", str};
        log.info("ZIP命令：{}", str);
        ExecUtils.exec(cmd, logUrl);
    }

    public static String initCadStr(String inputFilePath, String inputTypeStr, String outputTypeStr, String status, String outputFilePath) {
        String str;
        dataInit();
        if (cadGeneralType.contains(inputTypeStr) && cadGeneralType.contains(outputTypeStr) && "1".equals(status)) {
            str = "cd " + CAD_CONVERT_URL1 + " && " + CAD_CONVERT_TOOL1 + " " + inputFilePath + " --export " + outputFilePath;
        } else {
            str = "cd " + CAD_CONVERT_URL2 + " && " + CAD_CONVERT_TOOL2 + " -i " + inputFilePath + " -o " + outputFilePath;
        }
        log.info("CAD转换命令：{}", str);
        return str;
    }

    public static String initCaeStr(String inputFilePath, String outputTypeStr, String status, String outputFilePath) {
        String str;
        String convertUrl;
        String convertTool;
        dataInit();
        if (caeGeneralType.contains(outputTypeStr)) {
            convertUrl = CAE_CONVERT_URL3;
            convertTool = CAE_CONVERT_TOOL3;
            outputFilePath = StringUtils.getDirectoryPath(inputFilePath) + "/" + StringUtils.extractFileName(inputFilePath);
            // 创建文件夹
            File dirPath = new File(outputFilePath);
            dirPath.mkdir();
        } else if ("1".equals(status)) {
            convertUrl = CAE_CONVERT_URL1;
            convertTool = CAE_CONVERT_TOOL1;
        } else {
            convertUrl = CAE_CONVERT_URL2;
            convertTool = CAE_CONVERT_TOOL2;
        }
        str = "cd " + convertUrl + " && " + convertTool + " -i " + inputFilePath + " -o " + outputFilePath;
        log.info("CAE转换命令：{}", str);
        return str;
    }

    public static String initOutputFilePath(String inputFilePath, String outputTypeStr) {
        String outputFilePath = FileUtils.changeFileExtension(inputFilePath, outputTypeStr.toLowerCase());
        dataInit();
        if (caeGeneralType.contains(outputTypeStr)) {
            String directoryPath = StringUtils.getDirectoryPath(inputFilePath);
            String fileName = StringUtils.extractFileName(inputFilePath);
            outputFilePath = directoryPath + "/" + fileName + ".zip";
        } else if ("HDF5".equals(outputTypeStr)) {
            outputFilePath = FileUtils.changeFileExtension(inputFilePath, "h5");
        }
        return outputFilePath;
    }
}
